package com.cms.biz.rsf;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import com.cms.database.DBHelper;
import com.cms.facade.RequestFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.framework.CommandToken;

public class DeleteRSFCommand implements Command {

	private String next;

	public DeleteRSFCommand(String next) {
		this.next = next;
	}

	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		Connection conn = DBHelper.getConn();
		PreparedStatement pst = null;
		String[] setIds = req.getParameterValues("setId");

		if (!CommandToken.isValid(req)) {
			RequestFacade.setSuccessFlag(req, Boolean.FALSE);
			RequestFacade.setInvalidTokenMsg(req);
			return next;
		}

		if (setIds != null && setIds.length > 0) {

			try {
				pst = conn.prepareStatement(SQLString.DELETE_RSF);
				for (int i = 0; i < setIds.length; i++) {
					System.out.println(".." + setIds[i]);
					pst.setInt(1, Integer.parseInt(setIds[i]));
					pst.addBatch();
				}
				pst.executeBatch();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (pst != null) {
					try {
						pst.close();
						pst = null;
					} catch (final SQLException e) {
					}
				}
				DBHelper.closeConn(conn);
			}

		}
		return next;
	}

}
